import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from 'environments/environment';
import { promise } from "selenium-webdriver";
import { NzMessageService, NzNotificationService } from 'ng-zorro-antd';
import { ResolveEnd, Router } from '@angular/router';
import { AuthService } from '../..';

@Injectable()
export class HttpService {

  IP_PORT = environment.ip_port;
  PROJECT_PATH = '/api/services/app/';
  url = this.IP_PORT + this.PROJECT_PATH;

  constructor(public http: HttpClient,
    private _message: NzMessageService,
    private _notification: NzNotificationService,
    private router: Router
  ) {
  }

  /**
   * @register
   * @api /api/services/app/SystemUser/StudentRegister
   * @注册
   */

  register(data) {
    return this.http.post(this.url + 'SystemUser/StudentRegister', data);
  }

  registerPost(urls, data) {

    return this.http.post(this.url + urls, data);
  }
  registerGet(urls: string) {

    return this.http.get(this.url + urls);

  }
  /**
   * @login
   * @api /api/services/app/SystemUser/UserLogin
   * @登录
   */

  login(data) {
    return this.http.post(this.url + 'SystemUser/UserLogin', data);
  }

  post<T>(url: string, body: any): Promise<T> {
    return new Promise<T>((resolve, reject) => {
      this.http.post<any>(this.url + url, body).subscribe(value => {

        resolve(<T>(value.result));
      }, error => {
        this._showErrorMsg(error, reject);
      });
    }).catch(error => {
      if (error.statusText && (error.statusText === "Unknown Error" || error.statusText === "Internal Server Error")) {
        this._message.error('服务器错误，请联系管理员!');
      }
      throw new Error("未知错误");
    });
  }
  put<T>(url: string, body: any): Promise<T> {
    return new Promise<T>((resolve, reject) => {
      this.http.put<any>(this.url + url, body).subscribe(value => {
        resolve(<T>(value.result));
      }, error => {
        this._showErrorMsg(error, reject);
      });
    }).catch(error => {
      if (error.statusText && (error.statusText === "Unknown Error" || error.statusText === "Internal Server Error")) {
        this._message.error('服务器错误，请联系管理员!');
      }
      throw new Error("未知错误");
    });
  }
  get<T>(url: string): Promise<T> {
    return new Promise<T>((resolve, reject) => {
      this.http.get<any>(this.url + url).subscribe(value => {
        resolve(<T>(value.result));
      }, error => {
        this._showErrorMsg(error, reject);
      });
    }).catch(error => {
      if (error.statusText && (error.statusText === "Unknown Error" || error.statusText === "Internal Server Error")) {
        this._message.error('服务器错误，请联系管理员!');
      }
      throw new Error("未知错误");
    });
  }

  private _showErrorMsg(error: any, reject: (reason?: any) => void) {
    if ((error.error && error.error.unAuthorizedRequest) ||
      (error.unAuthorizedRequest !== undefined && error.unAuthorizedRequest === false)) {
      localStorage.setItem('authorization', JSON.stringify({}));
      this.router.navigate(['/login']);
      return;
    }
    if (error.error && error.error.error) {
      const resultErrot = error.error.error;
      if (resultErrot.validationErrors) {
        let strMsgError = '';
        (<Array<any>>resultErrot.validationErrors).forEach(e => strMsgError += e.message + '  ');
        this._notification.error('错误', strMsgError);
      } else {
        this._message.error(resultErrot.message ? resultErrot.message : resultErrot.details);
      }
      reject(resultErrot.message);
    } else {
      if (error.status) {
        if (error.status === 404) {
          this._message.error('未找到对应的服务内容！');
        } else {
          this._message.error('服务器错误，请联系管理员!');
        }
      }
      reject(error);
    }
  }
}
